package com.fagertveit.chainsawrus.graphics;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;

import android.opengl.GLES20;

import com.fagertveit.chainsawrus.io.FileIO;

public class SpriteSheet {
	private Texture texture;
	private ArrayList <Sprite>sprites = new ArrayList<Sprite>();
	
	public SpriteSheet(String filename, FileIO fileIO) {
		texture = new Texture(filename);
		texture.load(fileIO);
	}
	
	public int addSprite(float texX, float texY, float texWidth, float texHeight) {
		Sprite sprite = new Sprite(texX, texY, texWidth, texHeight);
		sprite.genUV(texture.getWidth(), texture.getHeight());
		int size = sprites.size();
		size++;
		sprites.add(sprite);
		
		return size;
	}
	
	public void render(int i, float x, float y) {
		Sprite sprite = sprites.get(i);
		
		float vertices[] = sprite.getVertices(x, y);
		
		short indices[] = {
			0, 1, 2, 2, 1, 3
		};
		
		FloatBuffer vertexBuffer = ByteBuffer.allocateDirect(vertices.length * 4)
        .order(ByteOrder.nativeOrder()).asFloatBuffer();
		vertexBuffer.put(vertices).position(0);
		
		ShortBuffer indexBuffer = ByteBuffer.allocateDirect(indices.length * 2)
        .order(ByteOrder.nativeOrder()).asShortBuffer();
		indexBuffer.put(indices).position(0);
		
		vertexBuffer.position(0);
	    GLES20.glVertexAttribPointer(0, 2, GLES20.GL_FLOAT, false, 4 * 4, vertexBuffer);
        
	    vertexBuffer.position(2);
        GLES20.glVertexAttribPointer(1, 2, GLES20.GL_FLOAT, false, 4 * 4, vertexBuffer);
        
        GLES20.glEnableVertexAttribArray(1);
        GLES20.glEnableVertexAttribArray(0);
        
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture.getTextureId());

        GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_SHORT, indexBuffer);
	}
}
